// pages/admin/adoption-manage/adoption-manage.js
const { get } = require('../../../utils/request')
const { formatDate, showError } = require('../../../utils/util')

Page({
  data: {
    adoptionList: [],
    statusIndex: 0,
    statusList: ['全部状态', '待审核', '已通过', '已拒绝'],
    stats: {
      total: 0,
      pending: 0,
      approved: 0,
      rejected: 0
    },
    loading: false
  },

  onLoad() {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.loadAdoptionList()
  },

  onShow() {
    this.loadAdoptionList()
  },

  onPullDownRefresh() {
    this.loadAdoptionList(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载领养申请列表
  loadAdoptionList(callback) {
    this.setData({ loading: true })

    const params = {}

    // 添加状态筛选
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusList[this.data.statusIndex]
    }

    get('/adoption/list', params).then(res => {
      const adoptionList = res.data || []
      
      // 格式化时间
      adoptionList.forEach(item => {
        item.createTime = formatDate(item.createTime)
        if (item.reviewTime) {
          item.reviewTime = formatDate(item.reviewTime)
        }
      })

      // 计算统计数据
      const stats = {
        total: adoptionList.length,
        pending: adoptionList.filter(item => item.status === '待审核').length,
        approved: adoptionList.filter(item => item.status === '已通过').length,
        rejected: adoptionList.filter(item => item.status === '已拒绝').length
      }

      this.setData({
        adoptionList,
        stats
      })
    }).catch(err => {
      showError('加载失败')
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value)
    })
    this.loadAdoptionList()
  },

  // 刷新
  onRefresh() {
    this.loadAdoptionList()
  },

  // 查看宠物详情
  viewPetDetail(e) {
    const petId = e.currentTarget.dataset.petId
    wx.navigateTo({
      url: `/pages/pet-detail/pet-detail?id=${petId}`
    })
  },

  // 审核申请
  reviewApplication(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/adoption-review/adoption-review?id=${id}`
    })
  }
})
